<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString
 * @LastEditTime: 2024-06-26 21:14:22
 * @FilePath: /chain-link-api-front/src/views/withdrawalCurrency/index.vue
 * @Description: 提币审核

  changelog: 提币申请功能取消 2024-5-24
-->
<template>
  <Header>
    <template #title>{{ t('title.WithdrawalCurrency') }}</template>
  </Header>
  <!-- 头部搜索框 -->
  <div class="searchBar">
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-row :gutter=20>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item :label="t('table.TxHash2')" style="width: 90%;">
            <el-input v-model.trim="queryParams.TxHash" :placeholder="t('global.PleaseInput') + t('table.TxHash')"/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item :label="t('table.ChainName')" style="width: 90%;">
            <el-input v-model.trim="queryParams.chainName"
                      :placeholder="t('global.PleaseInput') + t('table.ChainName')"
                      clearable/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <!-- 开始时间与结束时间 -->
          <el-form-item :label="t('table.Timestamp')" style="width: 90%;">
            <el-date-picker v-model="queryParams.time" type="datetimerange"
                            :start-placeholder="t('recharge.StartTime')"
                            :end-placeholder="t('recharge.EndTime')" format="YYYY-MM-DD HH:mm:ss"
                            date-format="YYYY-MM-DD"
                            time-format="hh:mm:ss"/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item :label="t('callback.ToAddress')" style="width: 90%;">
            <el-input v-model.trim="queryParams.address"
                      :placeholder="t('global.PleaseInput') + t('callback.ToAddress')">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item :label="t('table.Symbol')" style="width: 90%;">
            <el-input v-model.trim="queryParams.tokenSymbol"
                      :placeholder="t('global.PleaseInput') + t('table.Symbol')"
                      clearable/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="4" style="width: 90%;">
          <el-form-item :label="t('withdrawal.ExamineStatus')" style="width: 250px">
            <el-select v-model.trim="queryParams.status"
                       :placeholder="t('global.PleaseSelect') + t('withdrawal.ExamineStatus')" clearable>
              <el-option v-for="(item, index) in examineStatusOptions" :key="index" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
 
        <el-col :xs="24" :sm="12" :md="4">
          <el-form-item class="btns" >
            <el-button type="primary" :icon="Search" round @click="onSubmit"> {{ t('button.Search') }}</el-button>
            <el-button type="default" :icon="Refresh" round plain @click="onReset">{{ t('button.Reset') }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>


  <!-- 双重认证开关 -->
  <div class="secondReview">
    <div class="secondReview_title">{{ t('global.SecondReview') }}</div>
    <el-tooltip class="box-item" effect="dark" :content="t('message.SecondReviewTips')" placement="top" >
      <el-icon style="margin-right: .1rem"><QuestionFilled /></el-icon>
    </el-tooltip>
    <el-switch style="margin-right:.1rem" v-model="secondReview" :active-value="1" :inactive-value="0" @change="updateVerifyStatus"/>
  </div>


  <div class="table">
    <el-table :data="tableData" style="width: 100%; height: 600px;" v-loading="loading" border>
      <el-table-column prop="txHash" :label="t('table.TxHash2')" width="580" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="to" :label="t('callback.ToAddress')" width="420" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="value" :label="t('table.Amount')" width="100" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="callBack" :label="t('table.CallBackUrl')" width="350" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="businessId" :label="t('withdrawal.BusinessId')" width="120"
                       align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="memo" :label="t('withdrawal.Memo')" width="300" align="center" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.memo === "" ? "-" : scope.row.memo }}
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="t('withdrawal.ExamineStatus')" width="100" align="center" fixed="right">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ formatExamineStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="chainName" :label="t('table.ChainName')" width="120" align="center" fixed="right">
      </el-table-column>
      <el-table-column prop="tokenSymbol" :label="t('table.Symbol')" width="130" align="center"
                       fixed="right"></el-table-column>
      <el-table-column prop="timestamp" :label="t('table.Timestamp')" width="170" align="center" fixed="right">
        <template #default="scope">
          {{ formatTimestamp(scope.row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="t('global.Operation')" width="150" align="center">

        <template #default="scope">
          <el-popconfirm :title="t('withdrawal.Confirm')" @confirm="confirmSubmit(scope, 'agree')">
            <template #reference>
              <el-button link type="primary" size="small"
                         :disabled="scope.row.status === 1 || scope.row.status === 2 || scope.row.status === 3">
                {{ t('button.Confirm') }}
              </el-button>
            </template>
          </el-popconfirm>

              <el-button link type="danger" size="small" @click="confirmSubmit(scope,'refuse')"
                         :disabled="scope.row.status === 1 || scope.row.status === 2 || scope.row.status === 3">
                {{ t('button.Refused') }}
              </el-button>

        </template>
      </el-table-column>

    </el-table>

  </div>
  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>


  <!--  拒绝提币 备注 -->
    <el-dialog v-model="memoDialog" :title="t('message.EnterMemo')" width="500" center>
      <el-form :model="memoForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="备注">
          <el-input v-model="memoForm.memo" :placeholder="t('message.EnterMemo')"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelMemo">{{ t('global.Cancel')}}</el-button>
          <el-button type="primary" @click="submit()">
            {{ t('global.Submit')}}
          </el-button>
        </div>
      </template>
    </el-dialog>


  <!--  提币申请 已经取消 -->
  <!--  <el-dialog v-model="centerDialogVisible" title="提币申请" width="500" center>-->
  <!--    <el-form :model="forms" label-width="auto" style="max-width: 600px">-->
  <!--      <el-form-item label="链名称">-->
  <!--        <el-select v-model="forms.selectedValue" placeholder="请选择">-->
  <!--          <el-option-->
  <!--              v-for="(item ,key) in selectList.list"-->
  <!--              :key="key"-->
  <!--              :label="item.chainName" :value="item.chainId"/>-->
  <!--        </el-select>-->
  <!--      </el-form-item>-->
  <!--      <el-form-item label="回调地址">-->
  <!--        <el-input v-model="forms.callUrl" placeholder="请输入回调地址"/>-->
  <!--      </el-form-item>-->
  <!--      <el-form-item label="钱包地址">-->
  <!--        <el-input v-model="forms.address" placeholder="请输入钱包地址"/>-->
  <!--      </el-form-item>-->
  <!--      <el-form-item label="金额">-->
  <!--        <el-input v-model="forms.amount" placeholder="请输入提币金额"/>-->
  <!--      </el-form-item>-->
  <!--      <el-form-item label="备注">-->
  <!--        <el-input v-model="forms.memo" placeholder="请输入备注"/>-->
  <!--      </el-form-item>-->
  <!--    </el-form>-->

  <!--    <template #footer>-->
  <!--      <div class="dialog-footer">-->
  <!--        <el-button @click="centerDialogVisible = false">取消</el-button>-->
  <!--        <el-button type="primary" @click="submit">-->
  <!--          提交-->
  <!--        </el-button>-->
  <!--      </div>-->
  <!--    </template>-->
  <!--  </el-dialog>-->
</template>

<script setup>
import {reactive, ref, onMounted, unref, computed} from 'vue'
import {MD5} from 'crypto-js';
import {useUserStore} from "@/stores";
import {ElMessage, ElPagination} from "element-plus";
import {Search, Refresh, QuestionFilled} from '@element-plus/icons-vue'
import {formatTimestamp} from '../../utils/timeStamp.js'
import Header from "../layout/header.vue";
import {getConfigList, withdrawList, changeWithdrawStatus, getVerifyStatus, setVerifyStatus} from '../../require/api'
import {useI18n} from "vue-i18n";

const {t} = useI18n();

// 在组件被挂载后执行
onMounted(() => {
  getList()
  getChainList()
  getVerifyStatusFun() //获取提币审核状态
});


const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)
const chainList = ref([])
const centerDialogVisible = ref(false)
const w300 = ref(300)
const userStore = useUserStore()
const memoDialog = ref(false)
const secondReview = ref(0); // 双重认证 0:不需要双重认证  1:需要双重认证


// 拒绝提币备注
const memoForm = reactive([
  {
    memo: '',
  }
])

// 查询参数
const queryParams = reactive([
  {
    TxHash: '',
    address: '',
    chainName: '',
    tokenSymbol: '',
    time: [],
    startTime: '',
    endTime: '',
    status: ''
  }
])

// md5 小写32 加密
const randNumber = ref(); // 随机数
let timestamp = Date.now().toString(); // 当前时间戳（以毫秒为单位）
// 加密之后的sign = body + randNumber + timestamp
const sign = ref('');

const randBusinessId = ref(); // 随机数


const forms = reactive({
  selectedValue: '', // 选中值  展示 chainName 传 chainId
  callUrl: '', // 回调地址
  address: '', // 收款人钱包地址
  amount: '',  // 用户输入金额
  memo: '', // 提币备注

})





// 获取链列表
async function getChainList() {
  const {data} = await getConfigList()
  chainList.value = data
}

// 获取提币列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await withdrawList({
      pageIndex: pageIndex.value,
      pageSize: unref(pageSize),
      txHash: queryParams.TxHash,
      address: queryParams.address,
      startTime: queryParams.startTime,
      endTime: queryParams.endTime,
      chainName: queryParams.chainName,
      tokenSymbol: queryParams.tokenSymbol,
      status: queryParams.status
    })
    if (code === 200) {
      console.log(data)
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 审核状态 label
const examineStatusOptions = reactive([
  {value: 0, label: t('withdrawal.PendingReview')},
  {value: 1, label: t('withdrawal.ApprovedByReview')},
  {value: 2, label: t('withdrawal.ReviewRejection')},
  {value: 3, label: t('withdrawal.SuccessfulTransactions')},
  {value: 4, label: t('withdrawal.TransactionFailure')},
])

// 搜索方法
const onSubmit = () => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  queryParams.startTime = queryParams.time ? queryParams.time[0].getTime() / 1000 : '';
  queryParams.endTime = queryParams.time ? queryParams.time[1].getTime() / 1000 : '';
  getList();
}

// 清除  queryParams
const onClear = () => {
  queryParams.TxHash = ''
  queryParams.address = ''
  queryParams.time = ''
  queryParams.startTime = ''
  queryParams.endTime = ''
  queryParams.chainName = ''
  queryParams.tokenSymbol = ''
  queryParams.status = ''
}

// 重置方法
const onReset = () => {
  onClear();
  getList();
}

// 同意或者拒绝方法
async function changeWithdrawStatusFun(id, status, memo) {
  try {
    loading.value = true
    const {code, data, msg} = await changeWithdrawStatus({
      id,
      status: status,
      memo: memo
    })
    if (code === 200) {
      ElMessage.success(t('message.OperationSuccessful'))
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    memoDialog.value = false
    await getList()
  }
}

const refuse_id = ref('') //拒绝提币备注的id
const refuse_memo = ref('') //拒绝提币备注的备注

// 提交提币方法
async function confirmSubmit(scope, type) {
  console.log(scope.row)
  console.log(type)
  if (type === 'agree') {
    // 同意提币方法
    await changeWithdrawStatusFun(scope.row.id, 1)
  } else if (type === 'refuse') {
    refuse_id.value = scope.row.id
    memoDialog.value = true
    console.log(55555)

  }
}

// 提交拒绝提币
async function submit(){
  // 拒绝提币方法
  await changeWithdrawStatusFun(refuse_id.value, 2, memoForm.memo)
}

// 取消填写备注
function cancelMemo(){
  memoForm.memo = ''
  memoDialog.value = false
}

// 根据订单状态返回对应的el-tag类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0:
      return 'default'; // 待审核
    case 1:
      return 'success'; // 审核通过
    case 2:
      return 'warning'; // 审核驳回
    case 3:
      return 'success'; // 交易成功
    case 4:
      return 'danger'; // 交易失败

  }
};


// 获取提币审核状态
async function getVerifyStatusFun(){
  try {
      const {code, data, msg} = await getVerifyStatus()
  if( code === 200 ){
    // secondReview.value 转为number
    secondReview.value = data
    // const secondReview = data

  }else{
    ElMessage.error(msg)
  }
  } catch (e) {
    console.log(e);
  }
}


// 修改提币审核状态
async function updateVerifyStatus(status){
  try {
    const { code, data, msg } = await setVerifyStatus({ status })
    if( code === 200){
      getList()
    }else{
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  }
}

// 审核状态
function formatExamineStatus(status) {
  switch (status) {
    case 0:
      return t('withdrawal.PendingReview');
    case 1:
      return t('withdrawal.ApprovedByReview');
    case 2:
      return t('withdrawal.ReviewRejection');
    case 3:
      return t('withdrawal.SuccessfulTransactions');
    case 4:
      return t('withdrawal.TransactionFailure');
  }
}

// 提交提币申请 已经取消
// const submit = () => {
//   centerDialogVisible.value = false;
//
//   // 生成六位随机数
//   randNumber.value = String(Math.floor(Math.random() * 10000000));
//   randBusinessId.value = String(Math.floor(Math.random()));
//
//   const body = JSON.stringify({
//     callUrl: forms.callUrl,
//     mainCoinType: forms.selectedValue,
//     merchantId: localStorage.getItem('userId'),
//     address:forms.address,
//     amount:forms.amount,
//     businessId: randNumber.value,
//
//     memo: forms.memo
//
//   });
//   // 使用 MD5 算法对字符串进行加密，并转换为小写的 32 位十六进制字符串
//   const text = body + localStorage.getItem('token') + unref(randNumber) + timestamp;
//   console.log(text)
//   const sign = MD5(text).toString()
//
//   // 提币申请
//   withdraw({
//     body,
//     nonce: unref(randNumber),
//     timestamp: timestamp,
//     sign
//   }).then((res) => {
//     console.log(res)
//   })
// }


// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>


<style scoped lang="less">
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

// 双重认证
.secondReview{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .secondReview_title{
    margin-right: 10px;
  }
}


</style>